import * as echarts from '../../ec-canvas/echarts';

let historyChart = null;
let forecastChart = null;

function initHistoryChart(canvas, width, height, dpr) {
  historyChart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });
  canvas.setChart(historyChart);

  const option = {
    title: {
      text: '历史价格趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      name: '价格(元/kg)'
    },
    series: [
      {
        name: '历史价格',
        type: 'line',
        data: [],
        itemStyle: {
          color: '#07c160'
        }
      }
    ]
  };

  historyChart.setOption(option);
  return historyChart;
}

function initForecastChart(canvas, width, height, dpr) {
  forecastChart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });
  canvas.setChart(forecastChart);

  const option = {
    title: {
      text: '未来7天预测',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      name: '价格(元/kg)'
    },
    series: [
      {
        name: '预测价格',
        type: 'line',
        data: [],
        itemStyle: {
          color: '#1989fa'
        }
      }
    ]
  };

  forecastChart.setOption(option);
  return forecastChart;
}

Page({
  data: {
    historyEc: {
      onInit: initHistoryChart
    },
    forecastEc: {
      onInit: initForecastChart
    },
    regions: [
      {"label": "北京市", "value": 110000},
      {"label": "天津市", "value": 120000},
      {"label": "河北省", "value": 130000},
      {"label": "山西省", "value": 140000},
      {"label": "内蒙古自治区", "value": 150000},
      {"label": "辽宁省", "value": 210000},
      {"label": "吉林省", "value": 220000},
      {"label": "黑龙江省", "value": 230000},
      {"label": "上海市", "value": 310000},
      {"label": "江苏省", "value": 320000},
      {"label": "浙江省", "value": 330000},
      {"label": "安徽省", "value": 340000},
      {"label": "福建省", "value": 350000},
      {"label": "江西省", "value": 360000},
      {"label": "山东省", "value": 370000},
      {"label": "河南省", "value": 410000},
      {"label": "湖北省", "value": 420000},
      {"label": "湖南省", "value": 430000},
      {"label": "广东省", "value": 440000},
      {"label": "广西壮族自治区", "value": 450000},
      {"label": "海南省", "value": 460000},
      {"label": "重庆市", "value": 500000},
      {"label": "四川省", "value": 510000},
      {"label": "贵州省", "value": 520000},
      {"label": "云南省", "value": 530000},
      {"label": "西藏自治区", "value": 540000},
      {"label": "陕西省", "value": 610000},
      {"label": "甘肃省", "value": 620000},
      {"label": "青海省", "value": 630000},
      {"label": "宁夏回族自治区", "value": 640000},
      {"label": "新疆维吾尔自治区", "value": 650000}
    ],
    regionIndex: 0,
    categories: [{
      id:1,
      value: "秸秆"
    },
    {
      id:2,
      value: "玉米芯"
    }],
    categoryIndex: 0,
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    maxEndDate: '2024-12-31',
    today: '',
    priceData: null
  },

  onLoad() {
    console.log(wx.env.USER_DATA_PATH);
    // 设置默认日期为当前日期
    const today = new Date();
    const startDate = new Date(today);
    startDate.setDate(today.getDate() - 20); // 默认显示最近20天的数据
    
    this.setData({
      startDate: this.formatDate(startDate),
      endDate: this.formatDate(today),
      maxEndDate: this.formatDate(today),
      today: this.formatDate(today)
    });
  },

  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  bindRegionChange(e) {
    this.setData({
      regionIndex: e.detail.value
    });
  },

  bindCategoryChange(e) {
    this.setData({
      categoryIndex: e.detail.value
    });
  },

  bindStartDateChange(e) {
    const startDate = e.detail.value;
    const start = new Date(startDate);
    const maxEnd = new Date(start);
    maxEnd.setDate(start.getDate() + 20);

    // 确保最大结束日期不超过今天
    const today = new Date(this.data.today);
    if (maxEnd > today) {
      maxEnd.setTime(today.getTime());
    }

    // 如果当前结束日期超过新的最大结束日期，则更新结束日期
    const currentEnd = new Date(this.data.endDate);
    if (currentEnd > maxEnd) {
      this.setData({
        startDate: startDate,
        endDate: this.formatDate(maxEnd),
        maxEndDate: this.formatDate(maxEnd)
      });
    } else {
      this.setData({
        startDate: startDate,
        maxEndDate: this.formatDate(maxEnd)
      });
    }
  },

  bindEndDateChange(e) {
    const endDate = e.detail.value;
    const start = new Date(this.data.startDate);
    const end = new Date(endDate);
    const diffDays = Math.ceil((end - start) / (1000 * 60 * 60 * 24));

    if (diffDays > 20) {
      wx.showToast({
        title: '时间范围不能超过20天',
        icon: 'none'
      });
      return;
    }

    // 确保结束日期不超过今天
    const today = new Date(this.data.today);
    if (end > today) {
      wx.showToast({
        title: '结束日期不能超过今天',
        icon: 'none'
      });
      return;
    }

    this.setData({
      endDate: endDate
    });
  },

  getPriceData() {
    const me = this;
    wx.showLoading({
      title: '加载中...',
    });

    const data = {
      region: this.data.regions[this.data.regionIndex].value,
      category: this.data.categories[this.data.categoryIndex].id,
      start_date: this.data.startDate,
      end_date: this.data.endDate
    }

    wx.request({
      url: "http://127.0.0.1:5000/price_prediction",
      method: 'GET',
      data: data,
      success: function (res) {
        const mockData = {
          dates: res.data.historical_date,
          history: res.data.historical_prices,
          forecast: res.data.future_prices
        };
        
        me.setData({
          priceData: mockData
        });

        me.updateCharts(mockData);
      },
      fail: function (err) {
        console.log(err)
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },

  updateCharts(data) {
    if (historyChart) {
      historyChart.setOption({
        xAxis: {
          data: data.dates
        },
        series: [
          {
            name: '历史价格',
            data: data.history
          }
        ]
      });
    }

    if (forecastChart) {
      // 获取未来7天的日期
      const lastDate = new Date(data.dates[data.dates.length - 1]);
      const forecastDates = [];
      for (let i = 1; i <= 7; i++) {
        const date = new Date(lastDate);
        date.setDate(lastDate.getDate() + i);
        forecastDates.push(this.formatDate(date));
      }

      forecastChart.setOption({
        xAxis: {
          data: forecastDates
        },
        series: [
          {
            name: '预测价格',
            data: data.forecast
          }
        ]
      });
    }
  },

  exportToCSV() {
    if (!this.data.priceData) {
      wx.showToast({
        title: '请先查询数据',
        icon: 'none'
      });
      return;
    }
    wx.downloadFile({
      url: `http://127.0.0.1:5000/export_csv?region=${this.data.regions[this.data.regionIndex].value}&category=${this.data.categories[this.data.categoryIndex].id}&start_date=${this.data.startDate}&end_date=${this.data.endDate}`, // 替换为实际的后端接口地址
      success(res) {
        if (res.statusCode === 200) {
          // 下载成功，保存文件到本地
          wx.saveFile({
            tempFilePath: res.tempFilePath,
            success(saveRes) {
              const savedFilePath = saveRes.savedFilePath;
              wx.showToast({
                title: '文件保存成功',
                icon: 'success'
              });
              console.log('文件已保存到:', savedFilePath);
              //C:\Users\flash\AppData\Local\微信开发者工具\User Data\3e5d725bf5abbd2bfd7bc047ee989e46\WeappSimulator\WeappFileSystem\o6zAJs_o3cqdur7hlV8sQveHhBW0\wxc6cb78ea5ab012af\store
              // 可以在这里提示用户下载成功，并提供打开文件的操作
              // wx.showModal({
              //   title: '下载成功',
              //   content: '是否打开文件？',
              //   success(modalRes) {
              //     if (modalRes.confirm) {
              //       wx.openDocument({
              //         filePath: savedFilePath,
              //         success() {
              //           console.log('文件打开成功');
              //         },
              //         fail(err) {
              //           console.error('文件打开失败:', err);
              //         }
              //       });
              //     }
              //   }
              // });
            },
            fail(err) {
              console.error('文件保存失败:', err);
            }
          });
        } else {
          console.error('下载失败，状态码:', res.statusCode);
        }
      },
      fail(err) {
        console.error('下载请求失败:', err);
      }
    });
  }
}); 